//
//  LGTBindPhoneVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/13.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import WisdomHUD

class LGTBindPhoneVC: LGTBaseVC {

    var codePhoneTextField:UITextField? // 验证码手机号视图
    var codeTextField:UITextField? // 验证码视图
    var codeBtn:LGTButton? //获取验证码
    var codeLoginBtn:UIButton?
    var loginInfo:Dictionary<String, Any>?
    var timer:Timer?
    var timeIndex:Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addNote()
    }
    
    override func setUI() {
        super.setUI()
        self.setBavBarStyle(navBarHiden: false, title: "绑定手机号", back: true)
        
        let descLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.center, textColor: TextColor, fontSize: CGFloat(15 * KRate), text: "为了保障账户安全，请先绑定手机")
        self.view.addSubview(descLabel)
        descLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.height.equalTo(KRate * 15)
            make.top.equalTo(NavBarH + 39 * KRate)
        }
        
        let phoneLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: 14, text: "+86")
        self.view.addSubview(phoneLabel)
        phoneLabel.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 76)
            make.height.equalTo(KRate * 14)
            make.top.equalTo(descLabel.snp_bottomMargin).offset(KRate * 84)
        }
        
        self.codePhoneTextField = LGTViewCreateUtil.share.createLGTTextFied(font: Font_Normal_14, keyBoardType: UIKeyboardType.numberPad, placeholder: "仅支持中国大陆手机号", textColor: TextColor, limitCout: 11)
        self.view.addSubview(self.codePhoneTextField!)
        self.codePhoneTextField!.snp.makeConstraints { (make) in
            make.left.equalTo(phoneLabel.snp_rightMargin).offset(KRate * 22)
            make.height.equalTo(KRate * 20)
            make.width.equalTo(KRate * 160)
            make.centerY.equalTo(phoneLabel)
        }
        
        let line:UIImageView = LGTViewCreateUtil.share.createLineView()
        self.view.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(-KRate * 75)
            make.height.equalTo(1)
            make.top.equalTo(phoneLabel.snp_bottomMargin).offset(KRate * 14)
        }
        
        self.codeTextField = LGTViewCreateUtil.share.createLGTTextFied(font: Font_Normal_14, keyBoardType: UIKeyboardType.numberPad, placeholder: "请输入验证码", textColor: TextColor,limitCout: 11)
        self.view.addSubview(self.codeTextField!)
        self.codeTextField!.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.height.equalTo(KRate * 20)
            make.width.equalTo(KRate * 90)
            make.top.equalTo(line).offset(KRate * 24)
        }
        
        
        self.codeBtn = LGTViewCreateUtil.share.createTextLGTButton(title: "获取验证码", font: Font_Normal_12, color: DisableColor, selectedColor: DisableColor)
        self.codeBtn?.isUserInteractionEnabled = true
        self.codeBtn?.addTarget(self, action: #selector(sendCodeAction), for: UIControl.Event.touchUpInside)
        self.view.addSubview(self.codeBtn!)
        self.codeBtn?.snp.makeConstraints({ (make) in
            make.right.equalTo(-KRate * 78)
            make.width.equalTo(KRate * 62)
            make.height.equalTo(14)
            make.centerY.equalTo(self.codeTextField!)
        })
        
        let line2:UIImageView = LGTViewCreateUtil.share.createLineView()
        self.view.addSubview(line2)
        line2.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(-KRate * 75)
            make.height.equalTo(1)
            make.top.equalTo(self.codeTextField!.snp_bottomMargin).offset(KRate * 14)
        }
        
        self.codeLoginBtn = LGTViewCreateUtil.share.createTextLGTButton(title: "绑定", font: Font_Normal_15, color: UIColor.white, selectedColor: UIColor.white, corner:CGFloat(KRate * 20))
        self.codeLoginBtn?.backgroundColor = DisableColor
        self.view.addSubview(self.codeLoginBtn!)
        self.codeLoginBtn!.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(KRate * -75)
            make.height.equalTo(40 * KRate)
            make.top.equalTo(line2.snp_bottomMargin).offset(KRate * 40)
        }
        
        self.codeLoginBtn!.addTarget(self, action: #selector(bindAction), for: UIControl.Event.touchUpInside)
    }
    
    @objc func bindAction(){
        let code:String = self.codeTextField?.text ?? ""
        let data:Dictionary<String, Any> = self.loginInfo?["data"] as? Dictionary<String, Any> ?? [:]
        let user_id:Int = data["user_id"] as? Int ?? 0
        let user_token:String = data["user_token"] as? String ?? ""
        let phone:String = self.codePhoneTextField?.text ?? ""
        let param:Dictionary<String, Any> = ["code":code,
                                             "bind_user_id": user_id,
                                             "bind_user_token":user_token,
                                             "phone": phone]
        LGTHttpUtil.httpUtil.requestData(url: Bind_Phone_URL, param: param, showMessage:true, success: { (json) in
            
            LGTViewUtil.share.loginAction(nav: self.navigationController, json: json, showMessage: false)
            
        }) { (json) in
            
        }
        
    }
    
    
    @objc func sendCodeAction(){
        if self.timeIndex > 0{
            return
        }
        
        if self.codePhoneTextField?.text?.count != 11{
            WisdomHUD.showError(text: "请输入正确的手机号码")
            return
        }
        
        weak var weakSelf = self
        let params:Dictionary<String, Any> = ["phone": self.codePhoneTextField!.text ?? "",
                                              "type": 3]
        LGTHttpUtil.httpUtil.requestData(url: Send_Code_URL, param: params, showMessage: true, success: { (json) in
            let state:Int = json["state"] as! Int
            if state == 0{
                weakSelf!.timeIndex = 60
                weakSelf!.createTimer()
            }
        }) { (json) in
            
        }
    }
    
    func closeTimer(){
        self.timer?.invalidate()
    }
    
    func createTimer(){
        if self.timeIndex <= 0{
            return
        }
        
        self.timer?.invalidate()
        weak var weakSelf = self
        self.timer = Timer.init(timeInterval: 1, repeats: true, block: { (timer:Timer) in
            weakSelf?.timeIndex -= 1
            weakSelf?.codeBtn?.setTitle("\(weakSelf!.timeIndex)S", for: UIControl.State.normal)
            weakSelf?.codeBtn?.setTitle("\(weakSelf!.timeIndex)S", for: UIControl.State.selected)
            if weakSelf!.timeIndex <= 0{
                weakSelf?.closeTimer()
                weakSelf?.codeBtn?.setTitle("获取验证码", for: UIControl.State.normal)
                weakSelf?.codeBtn?.setTitle("获取验证码", for: UIControl.State.selected)
            }
        })
        
        RunLoop.main.add(self.timer!, forMode: RunLoop.Mode.common)
        self.timer?.fire()
    }
    
    func addNote(){
        self.codePhoneTextField?.addTarget(self, action: #selector(textFieldChange), for: UIControl.Event.editingChanged)
        self.codeTextField?.addTarget(self, action: #selector(textFieldChange), for: UIControl.Event.editingChanged)
    }
    
    
    @objc private func textFieldChange(textField:UITextField){
        //验证码可不可以登录验证
        if self.codePhoneTextField?.text?.count == 11 && (self.codeTextField?.text?.count ?? 0 > 0){
            self.codeLoginBtn?.backgroundColor = YellowColor
            self.codeLoginBtn?.isUserInteractionEnabled = true
        }else{
            self.codeLoginBtn?.backgroundColor = DisableColor
            self.codeLoginBtn?.isUserInteractionEnabled = false
        }
        
        //验证码可点击验证
        if self.codePhoneTextField?.text?.count == 11{
            self.codeBtn?.isUserInteractionEnabled = true
            self.codeBtn?.setTitleColor(YellowColor, for: UIControl.State.normal)
            self.codeBtn?.setTitleColor(YellowColor, for: UIControl.State.selected)
        }else{
            self.codeBtn?.isUserInteractionEnabled = false
            self.codeBtn?.setTitleColor(DisableColor, for: UIControl.State.normal)
            self.codeBtn?.setTitleColor(DisableColor, for: UIControl.State.selected)
        }
    }
    
    deinit {
        self.closeTimer()
    }
    
}
